package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.company;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import java.net.URLEncoder;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.company.CompanyBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.company.CpyClassBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CCompanys;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CompanyExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ISysUserPlantConnService;
import com.xiaoxu.intranetweb.util.PermissionCheck;
import com.xiaoxu.intranetweb.util.SzResult;
import com.xiaoxu.intranetweb.util.WebFunctionUtil;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 公司查询控制器
 *
 * @author xiaoxu
 * @version 1.00
 * @date 2022/1/5 15:00
 * @since 1.0
 */
@RestController
@RequestMapping(value = "/company")
public class CompanyQueryController {
    @Autowired
    private CompanyBu companyBu;
    @Autowired
    private CpyClassBu cpyClassBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private ISysUserPlantConnService userPlantConnService;
    @Autowired
    private WebFunctionUtil webFunctionUtil;

    /**
     * 所有公司查询接口
     *
     * @param value:公司名称 className:公司类型
     * @return SzResult
     */
    @GetMapping("/getCo")
    public SzResult getCo(@RequestParam(value = "value", required = false) String value,
                          @RequestParam(value = "className", required = false) String className,
                          @RequestParam(value = "cpyClassClass", required = false) String cpyClassClass,
                          @RequestParam(value = "phone", required = false) String phone,
                          HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return companyBu.getCompany(value, className, phone, cpyClassClass, plantId);
    }


    /**
     * 公司供应商查询接口
     *
     * @return SzResult
     */
    @GetMapping("/getCoSupply")
    public String getCoSupply(HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        return "companySupply";
    }


    //新增单位
    @PostMapping("/addCompany")
    @PermissionCheck("company_addCompany")
    public SzResult addCompany(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String cpyCo = jsonObject.getString("cpyCo");
        String cpyChiCo = jsonObject.getString("cpyChico");
        String cpyShrtname = jsonObject.getString("cpyShrtname");
        String cpyCoClass = jsonObject.getString("cpyCoClass");
        String cpyAddr = jsonObject.getString("cpyAddr");
        String cpyPass = jsonObject.getString("cpyPass");
        String cpyTempLock = jsonObject.getString("cpyTempLock");
        String cpyLongitude = jsonObject.getString("cpyLongitude");
        String cpyLatitude = jsonObject.getString("cpyLatitude");
        String cpyLinkMan = jsonObject.getString("cpyLinkMan");
        String cpyLinkMode = jsonObject.getString("cpyLinkMode");
        String beizhu = jsonObject.getString("beizhu");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return companyBu.addCompany(cpyCo, cpyChiCo, cpyShrtname, cpyCoClass, cpyAddr, cpyPass, cpyTempLock, cpyLongitude, cpyLatitude, cpyLinkMan, cpyLinkMode,beizhu, token, plantId);
    }

    //删除单位
    @GetMapping("/delCompany")
    @PermissionCheck("company_delCompany")
    public SzResult delCompany(@RequestParam String cpyId,@RequestParam String id, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return companyBu.deleteCompany(id,cpyId, token, plantId);
    }

    //修改单位
    @PostMapping("/updateCompany")
    @PermissionCheck("company_updateCompany")
    public SzResult updateCompany(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");
        String cpyId = jsonObject.getString("cpyId");
        String cpyCo = jsonObject.getString("cpyCo");
        String cpyChico = jsonObject.getString("cpyChico");
        String cpyShrtname = jsonObject.getString("cpyShrtname");
        String cpyCoClass = jsonObject.getString("cpyCoClass");
        String cpyAddr = jsonObject.getString("cpyAddr");
        String cpyPass = jsonObject.getString("cpyPass");
        String cpyTempLock = jsonObject.getString("cpyTempLock");
        String cpyLongitude = jsonObject.getString("cpyLongitude");
        String cpyLatitude = jsonObject.getString("cpyLatitude");
        String cpyLinkMan = jsonObject.getString("cpyLinkMan");
        String cpyLinkMode = jsonObject.getString("cpyLinkMode");
        String beizhu = jsonObject.getString("beizhu");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return companyBu.updateCompany(id,cpyId, cpyCo, cpyChico, cpyShrtname, cpyCoClass, cpyAddr, cpyPass, cpyTempLock, cpyLongitude, cpyLatitude, cpyLinkMan, cpyLinkMode, beizhu,token, plantId);
    }

    //修改绑定点
    @PostMapping("/updateLoadSite")
//    @PermissionCheck("company_updateLoadSite")
    public SzResult updateLoadSite(@RequestBody JSONObject jsonObject,@RequestHeader("Authorization") String token, @RequestHeader("Plant-Id") String plantId) throws Exception {
      return   companyBu.updateLoadSite(jsonObject.getString("id"),jsonObject.getString("loadSite"),token,plantId);

    }


    /**
     * 导出excel
     *
     * @param jsonParam 传入的参数 filename 文件名  fields 实体类  ids 数据  isHeader 是否有表头
     * @param response  响应
     * @param request   请求
     * @return void 无返回值 IO流
     * @throws IOException          IO异常
     * @throws ExecutionException   异常
     * @throws InterruptedException 异常
     */
    @PostMapping("/exportExcel")
    public void exportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        /*if (!userInfoDao.getUserPermissionWeb(StpUtil.getLoginIdByToken(token).toString()).containsKey("company_exportExcel")) {
            response.sendError(403,"您没有导出公司excel的权限");
        }*/
        //实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
        //文件名
        String filename = jsonParam.getString("filename");
        //数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
        //是否有表头
        boolean isHeader = jsonParam.getBoolean("isHeader");
        String mode = jsonParam.getString("mode");
        Boolean original = jsonParam.getBoolean("original");
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
        String sheetName = jsonParam.getString("sheetName");
        String cpyCo = jsonParam.getString("cpyCo");
        String cpyCoClass = jsonParam.getString("cpyCoClass");
        Map<String, String> form = jsonParam.getObject("form", Map.class);
        Future<List<CompanyExcelEn>> listFuture = companyBu.exportExcel(fields, filename, ids, isHeader, mode, original, pager, sheetName, token, form, plantId);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<CompanyExcelEn> companyExcelEns = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), CompanyExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("车辆类型")
                .doWrite(companyExcelEns);
        response.getOutputStream().flush();
        response.getOutputStream().close();

    }

    //拿到厂内单位
    @GetMapping("/inPlantCo")
    public SzResult inPlantCo() throws Exception {
//        return companyBu.inPlantCo();
        //邹县专用
        return companyBu.inPlantCoZx();
    }
//充值收款单位，邹县专供
    @GetMapping("/inPlantCoZx")
    public SzResult inPlantCoZx() throws Exception {
        return companyBu.inPlantCoZx();
    }

    //拿到收货单位
    @GetMapping("/receivingCo")
    public SzResult receivingCo() throws Exception {
        return companyBu.receivingCo();
    }

    //拿到供货单位
    @GetMapping("/supplyCo")
    public SzResult supplyCo() throws Exception {
        return companyBu.supplyCo();
    }


    //查询单位类型
    @GetMapping("/getCoClass")
    public SzResult getCoClass(@RequestParam(value = "cpyClassId", required = false) String cpyClassId, @RequestParam(value = "cpyClassClass", required = false) String cpyClassClass, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return companyBu.getCoClass(cpyClassId, cpyClassClass, token, plantId);
    }

    //新增单位类型
    @PostMapping("/addCoClass")
    @PermissionCheck("company_addCoClass")
    public SzResult addCoClass(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String cpyClassName = jsonObject.getString("cpyClassName");
        String cpyClassRemark = jsonObject.getString("cpyClassRemark");
        String cpyClassClass = jsonObject.getString("cpyClassClass");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return companyBu.addCoClass(cpyClassName, cpyClassRemark, cpyClassClass, token, plantId);
    }

    //删除单位类型
    @GetMapping("/delCoClass")
    public SzResult delCoClass(@RequestParam() String cpyClassId, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return companyBu.delCoClass(cpyClassId, token, plantId);
    }

    //修改单位类型
    @PostMapping("/updateCoClass")
    @PermissionCheck("company_updateCoClass")
    public SzResult updateCoClass(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");
        String cpyClassName = jsonObject.getString("cpyClassName");
        String cpyClassRemark = jsonObject.getString("cpyClassRemark");
        String cpyClassClass = jsonObject.getString("cpyClassClass");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return companyBu.updateCoClass(id, cpyClassName, cpyClassRemark, cpyClassClass, token, plantId);
    }

    //    设置公司是否允许粉煤灰排临时车号

    //    public SzResult setifOnTemporaryAshTruckQueue(String id,Integer ifOn){
    @PostMapping("/ifOnTemporaryAshTruckQueue")
    public SzResult ifOnTemporaryAshTruckQueue(@RequestBody JSONObject jsonObject,HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");
        Integer ifOn = jsonObject.getInteger("ifOn");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        try {
            return companyBu.ifOnTemporaryAshTruckQueue(id, ifOn,token,plantId);
        } catch (Exception e) {
            e.printStackTrace();
            return SzResult.error(e.getMessage());
        }
    }

    //    设置车辆是否能以特权身份排队
//    public SzResult ifOnTruckQueue(String id, Integer ifOn, String token, String plantId) throws Exception {
    @PostMapping("/ifOnCpyQueueVip")
    public SzResult ifOnCpyQueueVip(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");
        Integer ifOn = jsonObject.getInteger("ifOn");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return companyBu.ifOnCpyQueueVip(id, ifOn, token, plantId);
    }
}
